package cqyt.manage;



import cqyt.dao.BasicDAO;
import cqyt.pojo.Aircraft;
import cqyt.pojo.ReconnaissanceAircraft;
import cqyt.pojo.TransportAircraft;
import cqyt.utils.JDBCUtilsByDruid;
import cqyt.utils.Utility01;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;


/**
 * @author 涵菜
 * @version 1.0
 * 管理类
 * 第六代机 20 30000 4 优秀 源相阵控 30
 */
public class Manager {
    private BasicDAO basicDAO;
    private static final int PLANES_FIXED_SIZE=10;

    // 查询飞机总数的方法
    public int getTotalAircraftCount() {
        String sql = "SELECT COUNT(*)  FROM aircrafts"; // 使用 SUM 函数计算总数
        return basicDAO.queryCount(sql);
    }


    public void addPlane() {

        System.out.println("请选择要添加的飞机类型：");
        System.out.println("1. 添加战斗机");
        System.out.println("2. 添加运输机");
        System.out.println("3. 添加侦察机");

        int selection = Utility01.readMenuSelection();
        int planeCount = getTotalAircraftCount();
        if (planeCount >= PLANES_FIXED_SIZE) {
            System.out.println("已超过飞机固定数量大小！");
            return;
        }

        switch (selection) {
            case 1:
                System.out.println("请按照以下顺序录入飞机信息：[飞机名称, 飞机数量, 飞行高度, 飞行速度, 隐身性能, 雷达型号, 载弹数量]，输入空格分隔");
                String[] inputPart = Utility01.readStringByLimit();
                if(addWarplane(inputPart)){
                    System.out.println("战斗机田添加成功");
                }else {
                    System.out.println("战斗机田添加失败");
                }
                break;

            case 2:
                System.out.println("请按照以下顺序录入飞机信息：[飞机名称, 飞机数量, 飞行高度, 飞行速度, 隐身性能, 雷达型号, 运输容量]，输入空格分隔");
                String[] transportInput = Utility01.readStringByLimit();
                if(addTransportAircraft(transportInput)){
                    System.out.println("传输机添加成功");
                }else {
                    System.out.println("传输机添加失败");
                }
                break;

            case 3:
                System.out.println("请按照以下顺序录入飞机信息：[飞机名称, 飞机数量, 飞行高度, 飞行速度, 隐身性能, 雷达型号,相机个数]，输入空格分隔");
                String[] reconnaissanceInput = Utility01.readStringByLimit();
                if(addReconnaissanceAircraft(reconnaissanceInput)){
                    System.out.println("侦察机添加成功");
                }else {
                    System.out.println("侦察机添加失败");
                }
                break;

            default:
                System.out.println("无效选择！！");
                break;
        }
    }





    /**
     * 添加战斗机
     * @param inputPart 输入的战斗机信息
     */
    public boolean addWarplane(String[] inputPart) {
        String planeName = inputPart[0];
        int quantity = Integer.parseInt(inputPart[1]);
        int flightAltitude = Integer.parseInt(inputPart[2]);
        int flightSpeed = Integer.parseInt(inputPart[3]);
        int cameraCount=Integer.parseInt(inputPart[6]);
       int update= basicDAO.update("insert into aircrafts(id,name, type, quantity, flight_altitude, flight_speed, stealth_performance, radar_model, camera_count) values (null,?,'战斗机',?,?,?,?,?,?)",
                planeName,quantity,flightAltitude,flightSpeed,inputPart[4],inputPart[5],cameraCount);
        if (update <= 0) {
            return false;
        }
        return true;
    }

    /**
     * 添加传输机
     * @param inputPart 输入的传输机信息
     */
     public boolean addTransportAircraft(String[] inputPart) {
         String planeName = inputPart[0];
         int quantity = Integer.parseInt(inputPart[1]);
         int flightAltitude = Integer.parseInt(inputPart[2]);
         int flightSpeed = Integer.parseInt(inputPart[3]);
         int capacity=Integer.parseInt(inputPart[6]);
         int update= basicDAO.update("insert into aircrafts(id,name, type, quantity, flight_altitude, flight_speed, stealth_performance, radar_model, capacity) values (null,?,'运输机',?,?,?,?,?,?)",
                 planeName,quantity,flightAltitude,flightSpeed,inputPart[4],inputPart[5],capacity);
         if (update <= 0) {
             return false;
         }
         return true;
     }



    /**
     * 添加侦察机
     * @param inputPart 输入的侦察机信息
     */
    public boolean addReconnaissanceAircraft(String[]inputPart) {
        String planeName = inputPart[0];
        int quantity = Integer.parseInt(inputPart[1]);
        int flightAltitude = Integer.parseInt(inputPart[2]);
        int flightSpeed = Integer.parseInt(inputPart[3]);
        int missileCount=Integer.parseInt(inputPart[6]);
        int update= basicDAO.update("insert into aircrafts(id,name, type, quantity, flight_altitude, flight_speed, stealth_performance, radar_model, missile_count) values (null,?,'侦察机',?,?,?,?,?,?)",
                planeName,quantity,flightAltitude,flightSpeed,inputPart[4],inputPart[5],missileCount);
        if (update <= 0) {
            return false;
        }
        return true;

    }

    /**
     * 查看飞机数据
     */
    public void viewPlanes() {
        int planeCount = getTotalAircraftCount();
        if (planeCount ==0) {
            System.out.println("目前没有飞机，请添加飞机");
        }
        List<Aircraft> myAircrafts = basicDAO.queryMultiple("select * from aircrafts", Aircraft.class);
        for (Aircraft myAircraft : myAircrafts) {
            System.out.println(myAircraft);
        }
        }

    /**
     * 修改飞机数据
     */
    public void updatePlane(){
        String aircraftName = Utility01.readString(5);
        // 查询飞机是否存在
        if (!isAircraftExists(aircraftName)) {
            System.out.println("未找到名称为 " + aircraftName + " 的飞机！");
            return;
        }
        // 提示用户输入需要修改的字段名和值
        System.out.println("请输入需要修改的字段名和值，用空格分割开（例如：载弹数量 20）:");
        String input=Utility01.readString(10);
        String[] parts = input.split("\\s+");
        if (parts.length != 2) {
            System.out.println("输入格式错误，请按照 '字段名 值' 的格式输入！");
            return;
        }
        String fieldName = parts[0];
        String fieldValue = parts[1];
        // 动态生成 SQL 语句
        String sql = "UPDATE aircrafts SET " + fieldName + " = ? WHERE name = ?";
            int affectedRows = basicDAO.update(sql, fieldValue, aircraftName);
            if (affectedRows > 0) {
                System.out.println("修改成功！");
            } else {
                System.out.println("未找到匹配的记录，修改失败！");
            }
        }
    private boolean isAircraftExists(String aircraftName) {
        String sql = "SELECT COUNT(*) FROM aircrafts WHERE name = ?";
        int count = basicDAO.queryCount(sql, aircraftName);
        if(count>0) {
            return true;
        }
        return false;
    }
    /**
     * 删除军用飞机信息
     */
    public int deletePlane(String name) {
        // SQL 语句：根据名称删除飞机记录
        String sql = "DELETE FROM aircrafts WHERE name = ?";
        return basicDAO.delete(sql, name);
    }

    public void deleteAircraft() {
        System.out.print("请输入需要删除的飞机名称：");
        String planeName = Utility01.readString(6);
        // 执行删除操作
        try {
            int affectedRows = deletePlane(planeName);
            if (affectedRows > 0) {
                System.out.println("删除成功，已删除飞机名称为：" + planeName);
            } else {
                System.out.println("未找到对应飞机记录！");
            }
        } catch (Exception e) {
            System.err.println("删除失败：" + e.getMessage());
        }
    }

    public void executeAircraftTask(String name, int quantity) {
        // 查询当前飞机的数量
        int currentQuantity = basicDAO.queryCount(name);
        String sql = "SELECT COUNT(*) FROM aircrafts WHERE name = ?";
        // 验证飞机是否存在
        if (!basicDAO.queryScalar(sql,name)) {
            System.out.println("未找到对应飞机记录！");
            return;
        }

        if (currentQuantity == 0) {
            System.out.println("未找到对应飞机记录！");
            return;
        }

        if (currentQuantity < quantity) {
            System.out.println("无法完成任务！当前仅有 " + currentQuantity + " 架 " + name + " 可用。");
            return;
        }

        // 更新数据库中的飞机数量
        int updatedQuantity = currentQuantity - quantity;
        String sql2 = "UPDATE aircrafts SET quantity = ? WHERE name = ?";
        basicDAO.update(sql2,name,updatedQuantity);

        // 输出任务执行结果
        System.out.println("派出了 " + quantity + " 架 " + name + " 进行运输任务执行。");
    }

    /**
     * 派出军用飞机执行任务
     */
    public void selectPlaneToMission() {
        System.out.println("请输入需要执行任务的飞机名称和数量（用空格分隔）: ");
        String input = Utility01.readString(8);
        // 检验格式（\\s匹配空格字符）
        String[] inputPart = input.split("\\s+");
        if (inputPart.length != 2) {
            System.out.println("输入格式错误，请输入飞机名称和数量，用空格分隔！");
            return;
        }
        String planeName = inputPart[0];
        int planeQuantity ;
        try {
            planeQuantity = Integer.parseInt(inputPart[1]);
            if (planeQuantity <= 0) {
                System.out.println("飞机数量必须为正整数！");
                return;
            }
        } catch (NumberFormatException e) {
            System.out.println("飞机数量必须为数字！");
            return;
        }
        executeAircraftTask(planeName,planeQuantity);
    }

}


